/** @odoo-module **/
import init_grid_options from '../ag_grid/gridOptions.js'
import {toObj, formatId, keepTwoDecimal} from "../ag_grid/tool.js";
const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent
} = owl;


class CostModal extends Component {
    static template = xml`
        <div class="modal fade " id="CostModal" tabindex="-1">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h1 class="modal-title fs-5">
                            <t t-esc="state.headTitle"/>
                        </h1>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div t-ref="myGrid" style="width: 100%;height:400px" class="ag-theme-balham myGrid Canteen_cost_report_myGrid"/>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>      
    `;
    static props = {
        is_open: {type: Boolean,optional:true},
        data: {type: Object,optional:true}
    };

    setup() {
        this.state = useState({
            headTitle: '客户菜品售价',
            form: {},
            msg: '',
            haveChange:false,
        });
        this.myGrid_ref = useRef('myGrid');
        this.index = {};
        this.rowData = [];

        onMounted(() => {
            let _this = this;
            this.CostModal = new bootstrap.Modal('#CostModal', {
                toggle:'modal'
            });

            document.getElementById('CostModal').addEventListener('hidden.bs.modal', event => {
                // console.log(event);
                _this.state.haveChange = false;
                _this.gridOptions.api.setRowData([]);
                _this.env.closeCostModal();
            });

            let columnDefs = this.getColumnDefs();

            this.gridOptions = Object.assign({}, init_grid_options(), {
                groupDisplayType: 'custom',
                groupDefaultExpanded:1,//0
                suppressRowHoverHighlight:false,
                columnHoverHighlight: true,
                defaultColDef: {
                    editable: params => {
                        return false
                    },//单元表格是否可编辑
                    // resizable: true,//是否可以调整列大小，就是拖动改变列大小
                    // filter: true,  //开启刷选
                    // lockPinned: true
                    menuTabs: [],
                    flex: 1,
                    suppressMovable:true,
                },
                rowData: [],
                columnDefs:columnDefs,
                context: {
                    owl_widget: _this
                },
                onCellValueChanged: (e) => {
                    _this.onCellValueChanged(e);
                },
                getContextMenuItems: (e) => {
                    return [];
                },
                stopEditingWhenCellsLoseFocus:true,
                // pinnedTopRowData:[{}],
                // pinnedBottomRowData:[{}],
                // getRowStyle: (params) => {
                //     if (params.node.rowPinned) {
                //         return { backgroundColor: '#f5f7f7' };
                //     }
                //     if (!params.node.data) {
                //         return { backgroundColor: '#f5f7f7' };
                //     }
                // },
                // getRowClass: params => {
                //     let classArr = [];
                //     if (params && params.node && params.node.data && _this.getRowSpan(params, 'cost_top_type_name') > 1) {
                //         classArr.push('RowSpanFirst');
                //     }
                //     return classArr.join('  ');
                // },
            });
            this.agGrid = new agGrid.Grid(this.myGrid_ref.el, this.gridOptions);
        })

        onWillUpdateProps(nextProps => {
            // console.log(nextProps);
            if (nextProps.is_open) {
                return this.openModel(nextProps.data);
            }
        });

        this.handleSubmitModel = _.debounce(this.submitModel,300);

    }
    openModel(data) {
        let {
            rel_partner,
            cost_item_record,
            cost_object
        } = data;
        this.rel_partner = toObj(rel_partner,'id');
        this.cost_object = toObj(cost_object,'id');
        this.setRowData(cost_item_record);

        let headTitle = '成本明细';
        this.state.headTitle = headTitle;
        this.CostModal.show();
    }
    getColumnDefs(){
        let _this = this;
        let cols = [
            {
                field: 'date',
                headerName: '日期',
                width: 100,
                minWidth:100,
                maxWidth:100,
                filter:true
            },
            {
                field: 'cost_obj_id',
                headerName: '成本对象',
                flex:1,
                valueFormatter:(params)=>{
                    let value;
                    try {
                       return  _this.cost_object[params.value].name;
                    }catch (e) {
                        return ''
                    }
                },
            },
            {
                field: 'rel_partner_id',
                headerName: '交易对象',
                flex:1,
                valueFormatter:(params)=>{
                    let value;
                    try {
                        return  _this.rel_partner[params.value].name;
                    }catch (e) {
                        return ''
                    }
                },
            },
            {
                field: 'cost_amount',
                headerName: '成本',
                width: 100,
                minWidth:100,
                maxWidth:100,
            },
            {
                field: 'booked_cost_amount',
                headerName: '出库成本',
                width: 100,
                minWidth:100,
                maxWidth:100,
            },
            {
                field: 'cash_amount',
                headerName: '已付(元)',
                width: 100,
                minWidth:100,
                maxWidth:100,
            },
            {
                field: 'ap_amount',
                headerName: '未付(元)',
                width: 100,
                minWidth:100,
                maxWidth:100,
            },


        ];
        return cols
    }
    setRowData(data){
        let _this = this;
        let id = 0;
        let rowData = [];
        data.forEach(v=>{
            let { dinner_type_id, sales_category_id,cus_loc_id} = v;
            // console.log(_this.dinner_type_category[dinner_type_id]);
            id++;
            rowData.push({
                ...v,
                id:id
            })
        })
        this.gridOptions.api.setRowData(rowData);
    }

    // 单元格改变
    onCellValueChanged(params) {
        // console.log('-----onCellValueChanged----');
        // console.log(params);
        let colId = params.colDef.field;
        let newValue = params.newValue;
        let data = params.data;

        this.state.haveChange = true;

    }
    // 提交
    async submitModel() {
        await this.save();
        this.CostModal.hide();
    }
    async save(){
        let _this = this;

    }
    getRowData(id){
        let rowData = [];
        // console.log(id);
        this.gridOptions.api.forEachNode(function (node) {
            if(node.data){
                if(id){
                    node.data.id == id && (rowData.push(node.data));
                }else{
                    rowData.push(node.data);
                }
            }
        });
        // console.log(rowData);
        return rowData;
    }
}


export {
    CostModal
}
